<template>
<!-- 用户列表 -->
    <div>
      <!-- 面包屑 -->
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户列表</el-breadcrumb-item>
      </el-breadcrumb>
      <!-- 内容区 -->
      <el-card>
        <el-input
          placeholder="搜索用户"
          prefix-icon="el-icon-search"
          v-model="queryInfo.query" class='search' clearable @clear ='gouserdata'>
        </el-input>
        <el-button type="primary" @click="sear">搜索</el-button>
        <el-button type="primary" @click="dialogVisible = true">+添加用户</el-button>
        <!-- 添加用户弹出框 -->
        <el-dialog
          title="添加用户"
          :visible.sync="dialogVisible"
          width="30%"
          >
          
            <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px">
              <el-form-item label="用户名称" prop="username">
                <el-input v-model="ruleForm.username"></el-input>
              </el-form-item>
              <el-form-item label="密码" prop="password">
                <el-input v-model="ruleForm.password"></el-input>
              </el-form-item>
              <el-form-item label="手机号" prop="mobile">
                <el-input v-model="ruleForm.mobile"></el-input>
              </el-form-item>
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="ruleForm.email"></el-input>
              </el-form-item>
  
            </el-form>

          <span slot="footer" class="dialog-footer">
            <el-button @click="cancel">取 消</el-button>
            <el-button type="primary" @click="sure">确 定</el-button>
          </span>
        </el-dialog>
        <!-- 表格 -->
        <el-table
          :data="userdata"
          stripe
          style="width: 100%" border>
          <el-table-column
            type="index"
            label="编号"
            width="80px">
          </el-table-column>
          <el-table-column
            prop="username"
            label="用户名"
            width="180">
          </el-table-column>
          <el-table-column
            prop="email"
            label="邮箱"
            width="180">
          </el-table-column>
          <el-table-column
            prop="mobile"
            label="电话">
          </el-table-column>
          <el-table-column
            label="状态">
            <!-- slot-scope="scope"通过作用域插槽 ，获取当前这行数据信息-->
            <template slot-scope="scope">
              <!-- {{scope.row}} -->
                <el-switch
                v-model="scope.row.mg_state"
                active-color="#13ce66"
                inactive-color="#ff4949"
                @change ='gostate(scope.row)'>
                </el-switch>
            </template>
          </el-table-column>
          <el-table-column
            label="操作" width="212px">
            <template slot-scope="scope">
              <!-- {{scope.row}} -->
              <el-tooltip class="item" effect="dark" content="修改" placement="top-start" >
                <el-button type="primary" icon="el-icon-edit" @click="goRevise(scope.row)" style="margin-right:10px"></el-button>
              </el-tooltip>
                  <!-- 修改用户弹出框 -->
                  <el-dialog
                      title="修改用户信息"
                      :visible.sync="dialogRevise"
                      width="30%"
                      >
                      
                        <el-form :model="reviseForm" :rules="revise" ref="reviseForm" label-width="100px">
                          <el-form-item label="用户名称" prop="username">
                            <el-input v-model="reviseForm.username" disabled></el-input>
                          </el-form-item>
                          <el-form-item label="手机号" prop="mobile">
                            <el-input v-model="reviseForm.mobile"></el-input>
                          </el-form-item>
                          <el-form-item label="邮箱" prop="email">
                            <el-input v-model="reviseForm.email"></el-input>
                          </el-form-item>
              
                        </el-form>

                      <span slot="footer" class="dialog-footer">
                        <el-button @click="cancelRevise">取 消</el-button>
                        <el-button type="primary" @click="sureRevise(scope.row.id)">确 定</el-button>
                      </span>
                    </el-dialog>
              
              <el-tooltip class="item" effect="dark" content="删除" placement="top-start">
                <el-button type="danger" icon="el-icon-delete" @click="deletes(scope.row.id)"></el-button>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="分配权限" placement="top-start">
                <el-button type="warning" icon="el-icon-share" @click="openRights(scope.row)"></el-button>
              </el-tooltip>
              <!-- 分配用户权限 -->
                  <el-dialog
                      title="分配用户权限"
                      :visible.sync="userRight"
                      width="30%"
                      >
                      
                        <el-form :model="reviseForm" :rules="revise" ref="reviseForm" label-width="100px">
                          <el-form-item label="用户名称" prop="username">
                            <el-input v-model="rgihtsForm.username" disabled></el-input>
                          </el-form-item>
                          <el-form-item label="当前角色" prop="mobile">
                            <el-input v-model="rgihtsForm.role" disabled></el-input>
                          </el-form-item>
                          <el-form-item label="角色选择">
                            <el-select v-model="value" placeholder="请选择" :clearable="clear">
                              <el-option
                                v-for="item in options"
                                :key="item.id"
                                :label="item.roleName"
                                :value="item.id">
                              </el-option>
                            </el-select>
                          </el-form-item>
                          
                        </el-form>

                      <span slot="footer" class="dialog-footer">
                        <el-button @click="colseright">取 消</el-button>
                        <el-button type="primary" @click="surerights">确 定</el-button>
                      </span>
                    </el-dialog>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页功能 -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.pagenum"
          :page-sizes="[1, 2, 5, 10]"
          :page-size="2"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </el-card>

      
      
    </div>
</template>

<script>
export default {
    data() {
        return {
          search:'',
          queryInfo:{
            query:'',//获取的参数
            pagenum:1,//获取的页码
            pagesize:2//每页展示几条
          },
          userdata:[],
          total:0,
          dialogVisible:false,
          dialogRevise:false,
          userRight:false,
          clear:false,
          ruleForm:{
            username:'',
            password:'',
            email:'',
            mobile:''
          },
          reviseForm:{
            username:'',
            email:'',
            mobile:''
          },
          rgihtsForm:{
            username:'',
            role:'',
            id:''
          },
          value:'',
          options:[],
          rules: {//设置添加用户验证
          username: [
            { required: true, message: '请输入用户名', trigger: 'blur' },
            { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }],
          password: [
            { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 3, max: 8, message: '长度在 3 到 5 个字符', trigger: 'blur' }],
          mobile: [
            { required: true, message: '请输入手机号码', trigger: 'blur' },
            { min: 11, max: 11, message: '请输入正确的手机号码格式', trigger: 'blur' }],
          email: [
            { required: true, message: '请输入邮箱', trigger: 'blur' },
            { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }],
          },
          revise:{
          mobile: [
            { required: true, message: '请输入手机号码', trigger: 'blur' },
            { min: 11, max: 11, message: '请输入正确的手机号码格式', trigger: 'blur' }],
          email: [
            { required: true, message: '请输入邮箱', trigger: 'blur' },
            { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }],
          }
        };
    },
    created() {

    },
    mounted() {
      this.gouserdata()
    },
    methods: {
      async gouserdata(){
        const {data:ref} = await this.$http.get('users',{params:this.queryInfo});
        // console.log(ref);
        if(ref.meta.status =!200) return this.$message('获取列表失败');
        this.userdata = ref.data.users;
        this.total = ref.data.total
        
      },
      handleSizeChange(val) {//每页展示多少条数据
        this.queryInfo.pagesize = val
        this.gouserdata()
      },
      handleCurrentChange(val){//到第几页
        this.queryInfo.pagenum =val ;
        this.gouserdata()
      },
      async gostate(datas){
        const {data:ref} = await this.$http.put(`users/${datas.id}/state/${datas.mg_state}`);
        if(ref.meta.status != 200){ 
          datas.mg_state != datas.mg_state
          return this.$message.error('更新状态失败')}
          return this.$message.success('更新状态成功')
      },
      sear(){
        this.gouserdata()
      },
      cancel(){
        console.log('取消');
        this.dialogVisible =false;
        this.$refs.ruleForm.resetFields()
      },
      sure(){

        this.$refs.ruleForm.validate(async valid =>{
          if(!valid) return;
          const ref =await this.$http.post('users',this.ruleForm)
          // console.log(ref);
          if(ref.status != 200) return this.$message.error('添加用户失败');
          this.$message.success('添加用户成功');
          this.dialogVisible =false;
          this.gouserdata()
          
        })
          
       },
      async deletes(id){
        const con= await  this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).catch(err=>err)
        // console.log(con);
        if(con == 'cancel'){ 
          return this.$message.error('已取消删除')
        }
          const {data:ref} = await this.$http.delete('users/' +id)
          if(ref.status =! 200) return this.$message.error('删除用户失败')
          this.$message.success('删除用户成功')
          this.gouserdata()
       },
       //打开修改用户弹窗
       goRevise(data){
         this.dialogRevise =true
         console.log(data);
         this.reviseForm.email = data.email
         this.reviseForm.username = data.username
         this.reviseForm.mobile = data.mobile
         
       },
       //取消修改
       cancelRevise(){
         this.dialogRevise = false
       },
       //确定修改
       sureRevise(id){
         this.$refs.reviseForm.validate(async valid =>{
           if(!valid) return;
           const {data:ref} = await this.$http.put("users/"+id,{mobile:this.reviseForm.mobile,email:this.reviseForm.email})
         console.log(ref);
         if(ref.meta.status =!200) return this.$message.error('修改失败')
         this.$message.success('更新用户信息成功')
         this.dialogRevise =false
         this.gouserdata()
         })
       },
       //打开分配用户角色窗口
       async openRights(data){
         this.userRight = true
         this.rgihtsForm.username = data.username
         this.rgihtsForm.role = data.role_name
         this.rgihtsForm.id = data.id
         const {data:ref} = await this.$http.get('roles')
        //  console.log(ref);
         if(ref.meta.status =! 200) return this.$message.error('获取角色列表失败')
         this.options =ref.data
         },
      //确定选择角色
      async surerights(){
         const {data:res} = await this.$http.put(`users/${this.rgihtsForm.id}/role`,{rid:this.value})
        console.log(res);
        if(res.meta.status =!200) return this.$message.error('分配角色失败')
        this.$message.success('分配角色成功')
        this.userRight = false
        this.value =''
        this.gouserdata()
      },
      //取消分配
      colseright(){
        this.userRight = false
        this.value =''
      }
      
    }
};
</script>

<style scoped>
.el-card{
  margin-top: 20px;
}
.search{
  width: 200px;
  margin-right: 20px;
}
.el-table{
  margin-top: 20px;
}
</style>
